package com.lss.e_array;

/**
 * @author lss
 * @description 除自身以外数组的乘积
 * @createDate 2024/12/13-9:15
 * @tag 前缀
 */
public class lc_238 {
    public static void main(String[] args) {

    }

    public static int[] productExceptSelf(int[] nums) {
        int[] res = new int[nums.length];
        int prod = 1;
        for (int num : nums) {
            prod *= num;
        }
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == 0) {
                int temp = 1;
                for (int j = 0; j < nums.length; j++) {
                    if (j == i) {
                        continue;
                    }
                    temp *= nums[j];

                }
                res[i] = temp;
            } else
                res[i] = prod / nums[i];
        }

        return res;
    }


    /**
     * 前后缀乘积
     *
     * @param nums
     * @return
     */
    public static int[] productExceptSelf_0(int[] nums) {
        int len = nums.length;
        // 前缀乘积
        int[] preProd = new int[len];
        preProd[0] = 1;
        for (int i = 1; i < nums.length; i++) {
            preProd[i] = preProd[i - 1] * nums[i - 1];
        }
        // 后缀乘积
        int[] surfProd = new int[len];
        surfProd[len - 1] = 1;
        for (int i = len - 2; i >=0; i--) {
            surfProd[i] = surfProd[i + 1] * nums[i + 1];
        }
        for (int i = 0; i < len; i++) {
            nums[i] = surfProd[i] * preProd[i];
        }
        return nums;
    }

}
